<template>
  <div class="page-container">
    <!-- 将遮罩移动到main-card内部 -->
    <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <div class="loading-text">加载中，请稍候...</div>
    </div>

    <!-- 有数据 -->
    <div v-if="isDate">
      <el-card class="main-card">
        
        <div class="card-header">
          <h2>运营数据概览</h2>
        </div>
        <div class="card-container">
          <el-card
            v-for="(item, index) in allOperationData"
            :key="index"
            class="operation-card"
          >
            <div class="card-content">
              <div class="card-info">
                <h3>{{ item.title }}</h3>
                <p class="value">
                  {{ index === 3 ? Math.round(item.value) : item.value }}
                  <span style="font-size: 16px">
                    {{ { 0: "人", 1: "人", 2: "次", 3: "%" }[index] }}
                  </span>
                </p>
              </div>
            </div>
          </el-card>
        </div>
      </el-card>
      <el-card class="main-card chart-card">
        <div ref="lineChartRef" class="chart-container"></div>
      </el-card>
      <el-card class="main-card chart-card" style="margin-top: 20px">
        <div ref="barChartRef" class="chart-container"></div>
      </el-card>
    </div>
    <!-- 没数据  -->
     <div v-if="!isDate && !loading" class="no-data-prompt">
      <span class="empty-icon">📭</span>
      <div class="empty-text">当前时段暂无运营数据</div>
     </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  onBeforeUnmount,
  nextTick,
} from "vue";
import * as echarts from "echarts";
import http from "@/libs/http";
import { useRoute } from "vue-router";
const route = useRoute();
// 图表一
const lineChartRef = ref(null);
// 图表二
const barChartRef = ref(null);
// 所有数据
let allOperationData = ref("");

// 加载弹窗
const loading = ref(false);

//是否有显示数据
const isDate = ref(false);

let chartInstance = null;
let lineChartInstance = null;
let barChartInstance = null;

// 运营数据

const generateRandomColors = (count) => {
  const hueStep = 360 / count;
  return Array.from({ length: count }, (_, i) => {
    const hue = Math.round(i * hueStep + Math.random() * 20 - 10);
    const saturation = 60 + Math.random() * 35;
    const lightness = 40 + Math.random() * 30;
    return hslToRgb(hue % 360, saturation, lightness);
  });
};

const hslToRgb = (h, s, l) => {
  s /= 100;
  l /= 100;
  const k = (n) => (n + h / 30) % 12;
  const a = s * Math.min(l, 1 - l);
  const f = (n) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
  const alpha = Math.floor(180 + Math.random() * 75)
    .toString(16)
    .padStart(2, "0");
  return `#${[f(0), f(8), f(4)]
    .map((x) =>
      Math.round(x * 255)
        .toString(16)
        .padStart(2, "0")
    )
    .join("")}${alpha}`;
};

// 图表一
const initLineChart = () => {
  if (!lineChartRef.value) return;

  const option = {
    grid: {
      top: 80,
      bottom: 40,
      left: 80,
      right: 120,
      containLabel: true,
    },
    title: {
      text: "用户访问量数据",
      left: "center",
    },
    legend: {
      data: operationData.map((item) => item.title),
      bottom: -6,
      type: "scroll",
      formatter: function (name) {
        return name.split("").reduce((str, char, index) => {
          return index % 10 === 9 ? str + char + "\n" : str + char;
        }, "");
      },
      itemHeight: 14,
      itemGap: 15,
    },
    xAxis: {
      type: "category",
      data: dataDayList.value.map((item) => `${item}`),
    },
    yAxis: [
      {
        name: "单位(人数)",
        nameLocation: "start",
        nameGap: -20,
        position: "start",
        nameTextStyle: {
          color: "#666",
          fontSize: 12,
        },
      },
    ],
    series: operationData.map((item, index) => ({
      name: item.title,
      data: item.hourData,
      type: "line",
      lineStyle: {
        width: 3,
      },
      tooltip: {},
    })),
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
    },
  };

  if (lineChartRef.value) {
    lineChartInstance = echarts.init(lineChartRef.value);
    lineChartInstance.setOption(option);
  } else {
    console.error("图表容器未找到");
  }
  lineChartInstance.setOption(option);
};

// 图表二
const initBarChart = () => {
  if (!barChartRef.value) return;

  const option = {
    grid: {
      top: 80,
      bottom: 40,
      left: 80,
      right: 120,
      containLabel: true,
    },
    title: {
      text: "站点项目转化率趋势",
      left: "center",
    },
    legend: {
      data: barChartData.map((item) => item.title),
      bottom: -6,
      type: "scroll",
      formatter: function (name) {
        return name.split("").reduce((str, char, index) => {
          return index % 10 === 9 ? str + char + "\n" : str + char;
        }, "");
      },
      itemHeight: 14,
      itemGap: 15,
    },
    xAxis: {
      type: "category",
      data: dataDayList.value.map((item) => `${item}`),
    },
    yAxis: [
      {
        name: "单位(%)",
        nameLocation: "start",
        nameGap: -20,
        position: "start",
        nameTextStyle: {
          color: "#666",
          fontSize: 12,
        },
      },
    ],
    series: barChartData.map((item, index) => ({
      name: item.title,
      data: item.hourData,
      type: "line",
      lineStyle: {
        width: 3,
      },
      tooltip: {},
    })),
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
    },
  };

  if (barChartRef.value) {
    barChartInstance = echarts.init(barChartRef.value);
    barChartInstance.setOption(option);
  } else {
    console.error("图表容器未找到");
  }
  barChartInstance.setOption(option);
};

//图表一数据
const operationData = reactive([
  {
    title: "",
    hourData: "",
  },
  {
    title: "",
    hourData: "",
  },
  {
    title: "",
    hourData: "",
  },
]);

// 图表二数据
const barChartData = reactive([
  {
    title: "",
    hourData: "",
  },
]);

const dataDayList = ref([]);

// 获取运营数据列表
const getOperatingData = async () => {
  try {
    let param = {
      token: localStorage.getItem("openid"),
      activity_id: Number(route.query.site),
    };
    loading.value = true;
    const res = await http.$post(
      "/hd_project/Backend/getOperatingData",
      param
    );
    if (res.code == 200) {
      loading.value = false;
      isDate.value = true;
      allOperationData.value = res.data.total;
      const newData = res.data.dateDetail.requestCount.map(
        (i) => i.date || ""
      );

      // 更新访问量、留资人数、互动体验数、转化率
      operationData[0].hourData = res.data.dateDetail.requestCount.map(
        (i) => i.value || 0
      );
      operationData[1].hourData = res.data.dateDetail.userInfoCount.map(
        (i) => i.value || 0
      );
      operationData[2].hourData = res.data.dateDetail.experienceCount.map(
        (i) => i.value || 0
      );
      barChartData[0].hourData = res.data.dateDetail.transferPercent.map(
        (i) => Math.round(Number(i.value)) || 0
      );

      operationData[0].title = res.data.total[0].title;
      operationData[1].title = res.data.total[1].title;
      operationData[2].title = res.data.total[2].title;
      barChartData[0].title = res.data.total[3].title;
      console.log(
        operationData,
        "更新后的数据>>>>>>>>>>>>>>>>>>>",
        ">>>>>>>>>>>",
        res.data
      );

      nextTick(() => {
        // 图表一
        const option = {
          xAxis: {
            type: "category",
            data: newData.map((item) => `${item}`),
          },
          legend: {
            data: operationData.map((item) => item.title),
            bottom: -6,
            type: "scroll",
            formatter: function (name) {
              return name.split("").reduce((str, char, index) => {
                return index % 10 === 9 ? str + char + "\n" : str + char;
              }, "");
            },
            itemHeight: 14,
            itemGap: 15,
          },
          series: operationData.map((item, index) => ({
            name: item.title,
            data: item.hourData,
            type: "line",
            lineStyle: {
              width: 3,
            },
            tooltip: {},
          })),
        };
        // 图表二
        const option_b = {
          xAxis: {
            type: "category",
            data: newData.map((item) => `${item}`),
          },
          legend: {
            data: barChartData.map((item) => item.title),
            bottom: -6,
            type: "scroll",
            formatter: function (name) {
              return name.split("").reduce((str, char, index) => {
                return index % 10 === 9 ? str + char + "\n" : str + char;
              }, "");
            },
            itemHeight: 14,
            itemGap: 15,
          },
          series: barChartData.map((item, index) => ({
            name: item.title,
            data: item.hourData,
            type: "line",
            lineStyle: {
              width: 3,
            },
            tooltip: {},
          })),
        };

        dataDayList.value = newData;
        // 图表一
         initLineChart();
         // 图表二
         initBarChart();
        lineChartInstance.setOption(option);
        barChartInstance.setOption(option_b);
      });
    } else {
      loading.value = false;
      isDate.value = false;
      console.log(">>>>>>>>没拿到数据");
    }
  } catch (error) {
    loading.value = false;
    isDate.value = false;
    console.error("获取运营数据失败:", error);
  }
};
// 初始化
onMounted(() => {
  nextTick(() => {
    // 图表一
    initLineChart();
    // 图表二
    initBarChart();
    getOperatingData();
  });
  window.addEventListener("resize", () => {
    chartInstance?.resize();
    lineChartInstance?.resize();
    barChartInstance?.resize();
  });
});

onBeforeUnmount(() => {
  chartInstance?.dispose();
  lineChartInstance?.dispose();
  barChartInstance?.dispose();
});
</script>

<style scoped>
.no-data-prompt {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  animation: fadeIn 0.5s ease;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  color: #909399;
  letter-spacing: 1px;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.card-header h2 {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.main-card {
  position: relative; /* 确保相对定位 */
  background-color: #f5f7fa;
  margin: 30px;
  border-radius: 12px;
  min-height: 200px; /* 添加最小高度确保遮罩可见 */
}

.page-container {
  position: relative;
  min-height: 78vh;
  padding: 20px;
}

.loading-overlay {
  position: absolute; /* 相对于main-card定位 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10; /* 确保覆盖卡片内容 */
}

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.operation-card {
  margin-bottom: 20px;
  width: 280px;
  border-radius: 12px !important;
  transition: box-shadow 0.3s, transform 0.3s;
  background: linear-gradient(
    135deg,
    rgba(64, 158, 255, 0.08) 0%,
    rgba(103, 194, 58, 0.06) 100%
  );
  border: 1px solid rgba(64, 158, 255, 0.12);
}

.operation-card:nth-child(2n) {
  background: linear-gradient(
    135deg,
    rgba(103, 194, 58, 0.08) 0%,
    rgba(230, 162, 60, 0.06) 100%
  );
  border-color: rgba(103, 194, 58, 0.12);
}

.operation-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-content {
  padding: 20px;
}

.card-icon {
  margin-right: 15px;
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  margin-right: 20px;
  font-size: 32px;
  color: #409eff;
}

.card-info h3 {
  margin: 0 0 8px 0;
  color: #666;
}

.value {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.compare {
  color: #67c23a;
  font-size: 12px;
}

.chart-container {
  height: 700px;
  width: 100%;
  padding: 20px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3a7bb8;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 16px;
  color: #3a7bb8;
}
</style>
